#include <linux/sched.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <wait.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ipc.h>

int main(int argc, char ** argv){
	const int SIZE = 4096;
  const char * name = "OS";
  int shm_id;
  char *ptr;
  char tmp[4096];

  shm_id = shmget(0x2234,SIZE,IPC_CREAT | 0600 );
  ptr = (char*)shmat(shm_id,0,0);

  pid_t pid = fork();
	if(pid < 0) {
		fprintf(stderr, "Fork Failed");
	}
	else if(pid == 0) {

    char *str = argv[1];
		int len = strlen(argv[1]);
    if( (len > 0 && str[0] == '-') || len == 0 ) {
      sprintf(ptr, "%s is not a positive integer\n",str);
      return 0;
    }
    sprintf(tmp, "sqeunce is [");
    sprintf(ptr, "%s", tmp); ptr += strlen(tmp);

    int w = atoi(str);
    while(w != 1) {
      sprintf(tmp, "%d ",w);
      sprintf(ptr, "%s", tmp); ptr += strlen(tmp);
      w = (w & 1 ? 3*w+1 : (w>>1));
    }
    sprintf(tmp, "%d]\n", w);
    sprintf(ptr, "%s", tmp); ptr += strlen(tmp);
	}
	else {
		wait(NULL);
		printf("Child Complete\n");

    shm_id = shmget(0x2234,0,0);
    ptr = (char*)shmat(shm_id, NULL, 0);
    printf("%s\n",ptr);
    shmdt(ptr);
	}
	return 0;
}

